package com.newlink.building.common_base.utils

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.provider.Settings
import android.telephony.TelephonyManager
import androidx.annotation.RequiresPermission
import java.util.*

/**
 * 增强版设备工具类
 * @Author: Enhanced by Claude
 * @Date: 2025-09-15
 * @Description: 提供全面的设备信息获取和管理功能
 */
object DeviceUtilsEnhanced {

    /**
     * 设备信息数据类
     */
    data class DeviceInfo(
        val deviceId: String,
        val deviceName: String,
        val manufacturer: String,
        val model: String,
        val brand: String,
        val osVersion: String,
        val apiLevel: Int,
        val screenDensity: Float,
        val screenWidth: Int,
        val screenHeight: Int,
        val totalMemory: Long,
        val availableMemory: Long,
        val batteryLevel: Int,
        val isRooted: Boolean,
        val networkType: String
    )

    /**
     * 应用版本信息数据类
     */
    data class AppVersionInfo(
        val versionName: String,
        val versionCode: Long,
        val packageName: String,
        val firstInstallTime: Long,
        val lastUpdateTime: Long,
        val targetSdkVersion: Int,
        val minSdkVersion: Int
    )

    // ========== 版本信息 ==========

    /**
     * 获取应用版本号（兼容新旧API）
     */
    fun getAppVersionCode(context: Context): Long {
        return try {
            val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                packageInfo.longVersionCode
            } else {
                @Suppress("DEPRECATION")
                packageInfo.versionCode.toLong()
            }
        } catch (e: Exception) {
            EnhancedLogger.e("DeviceUtils", "获取版本号失败", e)
            -1L
        }
    }

    /**
     * 获取应用版本名称
     */
    fun getAppVersionName(context: Context): String {
        return try {
            val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0)
            packageInfo.versionName ?: "unknown"
        } catch (e: Exception) {
            EnhancedLogger.e("DeviceUtils", "获取版本名称失败", e)
            "unknown"
        }
    }

    /**
     * 获取完整的应用版本信息
     */
    fun getAppVersionInfo(context: Context): AppVersionInfo? {
        return try {
            val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0)
            val appInfo = packageInfo.applicationInfo

            AppVersionInfo(
                versionName = packageInfo.versionName ?: "unknown",
                versionCode = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                    packageInfo.longVersionCode
                } else {
                    @Suppress("DEPRECATION")
                    packageInfo.versionCode.toLong()
                },
                packageName = context.packageName,
                firstInstallTime = packageInfo.firstInstallTime,
                lastUpdateTime = packageInfo.lastUpdateTime,
                targetSdkVersion = appInfo.targetSdkVersion,
                minSdkVersion = appInfo.minSdkVersion
            )
        } catch (e: Exception) {
            EnhancedLogger.e("DeviceUtils", "获取应用版本信息失败", e)
            null
        }
    }

    // ========== 设备标识 ==========

    /**
     * 获取设备唯一标识符（隐私友好）
     */
    fun getDeviceId(context: Context): String {
        return try {
            Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID)
                ?: "unknown_device"
        } catch (e: Exception) {
            EnhancedLogger.e("DeviceUtils", "获取设备ID失败", e)
            "unknown_device"
        }
    }

    /**
     * 获取设备名称
     */
    fun getDeviceName(): String {
        return try {
            val manufacturer = Build.MANUFACTURER
            val model = Build.MODEL
            if (model.startsWith(manufacturer, ignoreCase = true)) {
                model.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() }
            } else {
                manufacturer.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() } + " " + model
            }
        } catch (e: Exception) {
            EnhancedLogger.e("DeviceUtils", "获取设备名称失败", e)
            "Unknown Device"
        }
    }

    // ========== 系统信息 ==========

    /**
     * 获取Android版本信息
     */
    fun getAndroidVersion(): String {
        return "${Build.VERSION.RELEASE} (API ${Build.VERSION.SDK_INT})"
    }

    /**
     * 检查是否为调试模式
     */
    fun isDebugMode(context: Context): Boolean {
        return try {
            val appInfo = context.applicationInfo
            (appInfo.flags and android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE) != 0
        } catch (e: Exception) {
            EnhancedLogger.e("DeviceUtils", "检查调试模式失败", e)
            false
        }
    }

    /**
     * 检查设备是否已Root
     */
    fun isDeviceRooted(): Boolean {
        return try {
            // 检查常见的Root文件
            val rootPaths = arrayOf(
                "/system/app/Superuser.apk",
                "/sbin/su",
                "/system/bin/su",
                "/system/xbin/su",
                "/data/local/xbin/su",
                "/data/local/bin/su",
                "/system/sd/xbin/su",
                "/system/bin/failsafe/su",
                "/data/local/su",
                "/su/bin/su"
            )

            rootPaths.any { java.io.File(it).exists() }
        } catch (e: Exception) {
            EnhancedLogger.e("DeviceUtils", "检查Root状态失败", e)
            false
        }
    }

    // ========== 硬件信息 ==========

    /**
     * 获取屏幕密度
     */
    fun getScreenDensity(context: Context): Float {
        return try {
            context.resources.displayMetrics.density
        } catch (e: Exception) {
            EnhancedLogger.e("DeviceUtils", "获取屏幕密度失败", e)
            1.0f
        }
    }

    /**
     * 获取屏幕分辨率
     */
    fun getScreenResolution(context: Context): Pair<Int, Int> {
        return try {
            val metrics = context.resources.displayMetrics
            Pair(metrics.widthPixels, metrics.heightPixels)
        } catch (e: Exception) {
            EnhancedLogger.e("DeviceUtils", "获取屏幕分辨率失败", e)
            Pair(0, 0)
        }
    }

    /**
     * 获取CPU架构
     */
    fun getCpuAbi(): String {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Build.SUPPORTED_ABIS.joinToString(", ")
        } else {
            @Suppress("DEPRECATION")
            "${Build.CPU_ABI}, ${Build.CPU_ABI2}"
        }
    }

    // ========== 网络信息 ==========

    /**
     * 获取网络类型
     */
    @RequiresPermission(Manifest.permission.READ_PHONE_STATE)
    fun getNetworkType(context: Context): String {
        return try {
            val telephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
            when (telephonyManager.networkType) {
                TelephonyManager.NETWORK_TYPE_GPRS,
                TelephonyManager.NETWORK_TYPE_EDGE,
                TelephonyManager.NETWORK_TYPE_CDMA,
                TelephonyManager.NETWORK_TYPE_1xRTT,
                TelephonyManager.NETWORK_TYPE_IDEN -> "2G"
                TelephonyManager.NETWORK_TYPE_UMTS,
                TelephonyManager.NETWORK_TYPE_EVDO_0,
                TelephonyManager.NETWORK_TYPE_EVDO_A,
                TelephonyManager.NETWORK_TYPE_HSDPA,
                TelephonyManager.NETWORK_TYPE_HSUPA,
                TelephonyManager.NETWORK_TYPE_HSPA,
                TelephonyManager.NETWORK_TYPE_EVDO_B,
                TelephonyManager.NETWORK_TYPE_EHRPD,
                TelephonyManager.NETWORK_TYPE_HSPAP -> "3G"
                TelephonyManager.NETWORK_TYPE_LTE -> "4G"
                else -> {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                        when (telephonyManager.networkType) {
                            TelephonyManager.NETWORK_TYPE_NR -> "5G"
                            else -> "Unknown"
                        }
                    } else {
                        "Unknown"
                    }
                }
            }
        } catch (e: Exception) {
            EnhancedLogger.e("DeviceUtils", "获取网络类型失败", e)
            "Unknown"
        }
    }

    // ========== 综合信息 ==========

    /**
     * 获取完整的设备信息
     */
    @RequiresPermission(Manifest.permission.READ_PHONE_STATE)
    fun getCompleteDeviceInfo(context: Context): DeviceInfo {
        val (screenWidth, screenHeight) = getScreenResolution(context)

        return DeviceInfo(
            deviceId = getDeviceId(context),
            deviceName = getDeviceName(),
            manufacturer = Build.MANUFACTURER,
            model = Build.MODEL,
            brand = Build.BRAND,
            osVersion = getAndroidVersion(),
            apiLevel = Build.VERSION.SDK_INT,
            screenDensity = getScreenDensity(context),
            screenWidth = screenWidth,
            screenHeight = screenHeight,
            totalMemory = getTotalMemory(),
            availableMemory = getAvailableMemory(context),
            batteryLevel = getBatteryLevel(context),
            isRooted = isDeviceRooted(),
            networkType = getNetworkType(context)
        )
    }

    /**
     * 获取总内存大小
     */
    private fun getTotalMemory(): Long {
        return try {
            val memInfo = Runtime.getRuntime()
            memInfo.maxMemory()
        } catch (e: Exception) {
            EnhancedLogger.e("DeviceUtils", "获取总内存失败", e)
            0L
        }
    }

    /**
     * 获取可用内存大小
     */
    private fun getAvailableMemory(context: Context): Long {
        return try {
            val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as android.app.ActivityManager
            val memoryInfo = android.app.ActivityManager.MemoryInfo()
            activityManager.getMemoryInfo(memoryInfo)
            memoryInfo.availMem
        } catch (e: Exception) {
            EnhancedLogger.e("DeviceUtils", "获取可用内存失败", e)
            0L
        }
    }

    /**
     * 获取电池电量
     */
    private fun getBatteryLevel(context: Context): Int {
        return try {
            val batteryStatus = context.registerReceiver(null,
                android.content.IntentFilter(android.content.Intent.ACTION_BATTERY_CHANGED))
            val level = batteryStatus?.getIntExtra(android.os.BatteryManager.EXTRA_LEVEL, -1) ?: -1
            val scale = batteryStatus?.getIntExtra(android.os.BatteryManager.EXTRA_SCALE, -1) ?: -1
            if (level != -1 && scale != -1) {
                (level * 100 / scale.toFloat()).toInt()
            } else {
                -1
            }
        } catch (e: Exception) {
            EnhancedLogger.e("DeviceUtils", "获取电池电量失败", e)
            -1
        }
    }

    /**
     * 记录设备信息到日志
     */
    @RequiresPermission(Manifest.permission.READ_PHONE_STATE)
    fun logDeviceInfo(context: Context) {
        val deviceInfo = getCompleteDeviceInfo(context)
        val versionInfo = getAppVersionInfo(context)

        EnhancedLogger.separator("DeviceInfo", "设备信息")

        val message = buildString {
            appendLine("📱 设备信息")
            appendLine("┌─────────────────────────────────────")
            appendLine("│ 设备名称: ${deviceInfo.deviceName}")
            appendLine("│ 制造商: ${deviceInfo.manufacturer}")
            appendLine("│ 型号: ${deviceInfo.model}")
            appendLine("│ 品牌: ${deviceInfo.brand}")
            appendLine("│ 系统版本: ${deviceInfo.osVersion}")
            appendLine("│ 屏幕分辨率: ${deviceInfo.screenWidth}x${deviceInfo.screenHeight}")
            appendLine("│ 屏幕密度: ${deviceInfo.screenDensity}")
            appendLine("│ 网络类型: ${deviceInfo.networkType}")
            appendLine("│ 电池电量: ${deviceInfo.batteryLevel}%")
            appendLine("│ Root状态: ${if (deviceInfo.isRooted) "已Root" else "未Root"}")
            appendLine("│ 调试模式: ${if (isDebugMode(context)) "开启" else "关闭"}")
            if (versionInfo != null) {
                appendLine("│ 应用版本: ${versionInfo.versionName} (${versionInfo.versionCode})")
                appendLine("│ 目标SDK: ${versionInfo.targetSdkVersion}")
            }
            append("└─────────────────────────────────────")
        }

        EnhancedLogger.i("DeviceUtils", message)
    }
}